from typing import List

from fastapi import APIRouter, Depends, HTTPException

from app.admin.schemas.tenant import Tenant, TenantCreate, TenantUpdate,TenantQuery
from app.admin.services.tenant_service import tenant_service
from app.models.user import User
from app.schemas.token import APIResponse
from app.security.auth import get_current_active_superuser, get_current_active_user

router = APIRouter()


@router.post("/", response_model=APIResponse[Tenant])
async def create_tenant(
        tenant: TenantCreate,
        current_user: User = Depends(get_current_active_superuser)
):
    """
    创建新租户（仅限超级用户）
    """
    if tenant.code is None:
        raise HTTPException(
            status_code=400,
            detail=APIResponse(code=400, msg=f"租户编码为空.", data=None)
        )
    if await tenant_service.check_code_exists(tenant.code):
        raise HTTPException(
            status_code=400,
            detail=APIResponse(code=400, msg=f"租户编码 [{tenant.code}] 已存在.", data=None)
        )

    created_tenant = await tenant_service.create_tenant(tenant=tenant)
    return APIResponse(
        code=200,
        msg=f"租户 [{created_tenant.code}] 创建成功",
        data=created_tenant
    )


@router.get("/", response_model=APIResponse[List[Tenant]])
async def read_tenants(
        query: TenantQuery = Depends(),
        current_user: User = Depends(get_current_active_superuser)
):
    """
    获取租户列表（仅限超级用户）
    支持按租户编码、名称、域名和激活状态筛选
    """
    tenants = await tenant_service.get_tenants(query)
    return APIResponse(
        code=200,
        msg="获取租户列表成功",
        data=tenants
    )


@router.get("/{tenant_id}", response_model=APIResponse[Tenant])
async def read_tenant(
        tenant_id: str,
        current_user: User = Depends(get_current_active_user)
):
    """
    根据ID获取租户信息（仅限超级用户）
    """
    db_tenant = await tenant_service.get_tenant(tenant_id=tenant_id)
    if db_tenant is None:
        raise HTTPException(
            status_code=400,
            detail=APIResponse(code=400, msg=f"租户 [{tenant_id}] 不存在", data=None)
        )
    return APIResponse(
        code=200,
        msg="获取租户信息成功",
        data=db_tenant
    )


@router.put("/{tenant_id}", response_model=APIResponse[Tenant])
async def update_tenant(
        tenant_id: str,
        tenant_update: TenantUpdate,
        current_user: User = Depends(get_current_active_superuser)
):
    """
    更新租户信息（仅限超级用户）
    """
    db_tenant = await tenant_service.get_tenant(tenant_id=tenant_id)
    if db_tenant is None:
        raise HTTPException(
            status_code=400,
            detail=APIResponse(code=400, msg=f"租户 [{tenant_id}] 不存在", data=None)
        )

    updated_tenant = await tenant_service.update_tenant(tenant_id=tenant_id, tenant_update=tenant_update)
    return APIResponse(
        code=200,
        msg=f"租户 [{updated_tenant.code}] 信息更新成功",
        data=updated_tenant
    )


@router.delete("/{tenant_id}", response_model=APIResponse[bool])
async def delete_tenant(
        tenant_id: str,
        current_user: User = Depends(get_current_active_superuser)
):
    """
    删除租户（仅限超级用户）
    """
    db_tenant = await tenant_service.get_tenant(tenant_id=tenant_id)
    if db_tenant is None:
        raise HTTPException(
            status_code=400,
            detail=APIResponse(code=400, msg=f"租户 [{tenant_id}] 不存在", data=None)
        )

    success = await tenant_service.delete_tenant(tenant_id=tenant_id)
    if not success:
        raise HTTPException(
            status_code=500,
            detail=APIResponse(code=500, msg=f"删除租户 [{tenant_id}] 失败", data=None)
        )

    return APIResponse(
        code=200,
        msg=f"租户 [{tenant_id}] 删除成功",
        data=True
    )

# @router.post("/{tenant_id}/users", response_model=APIResponse[UserSchema])
# async def create_tenant_user(
#         tenant_id: str,
#         user: UserCreate,
#         current_user: User = Depends(get_current_active_superuser)
# ):
#     """
#     创建租户用户（仅限超级用户）
#     """
#     # 检查租户是否存在
#     db_tenant = await tenant_service.get_tenant(tenant_id=tenant_id)
#     if db_tenant is None:
#         raise HTTPException(
#             status_code=400,
#             detail=APIResponse(code=400, msg=f"租户 [{tenant_id}] 不存在", data=None)
#         )
#
#     # 检查登录名是否已存在
#     if await user_service.check_login_name_exists(user.login_name):
#         raise HTTPException(
#             status_code=400,
#             detail=APIResponse(code=400, msg=f"登录名 [{user.login_name}] 已存在", data=None)
#         )
#
#     # 创建用户
#     created_user = await user_service.create_user(user=user)
#     return APIResponse(
#         code=200,
#         msg="用户创建成功",
#         data=created_user
#     )
